/*
* 1.请求所有报表
* 2.点击报表进入权限列表
* 3.新增自定义报表
* */
import React from "react";
import {connect} from 'react-redux';
import {Button, Popover, Modal, Form, Input} from 'antd';
import menuRoute from 'routes/menuRoute';
import {messages} from "share/common";
import ReportDistributionService from "containers/data-center/report-distribution/report-distribution.service";
import 'styles/data-center/report-distribution/report-distribution.scss';
import {LanguageInput} from 'components/index';
import ResizeTable from 'components/resize-table';

const FormItem = Form.Item;

class ReportDistribution extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isNewEnable: false,
      loading: true,
      reportObj: {
        reportCode: "",
        reportUrl: "",
        reportName: "",
        reportDesc: "",
        i18n: {},
      },
      newReport: false,
      modelKey: 1,
      pagination: {
        page: 0,
        total: 0,
        size: 10,
      },
      columns: [
        {
          /*序号*/
          title: messages('data-center.key1'/*序号*/),
          key: "_index",
          dataIndex: '_index',
          width: '10%',
        },
        {
          /*数据表*/
          title: messages('data-center.key2'/*数据表*/),
          key: "reportName",
          dataIndex: 'reportName',
          width: '40%',
          render: (text, record) => <span>{text ? <Popover placement="topLeft" content={text}>
            {record.reportType === "SD" ? <span className='tag-sd'>{messages('data-center.key55')/*定制*/}</span> : ""}
            {text}</Popover> : '-'}</span>
        },
        {
          /*描述*/
          title: messages('data-center.key3'/*描述*/),
          key: "reportDesc",
          dataIndex: 'reportDesc',
          width: '50%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
      ],
      //报表动态获取
      reportList: [],
    }
  }

  componentDidMount() {
    //记住页码
    let _pagination = this.getBeforePage('ReportDistribution');
    let {pagination} = this.state;
    pagination.page = _pagination.page;
    pagination.current = _pagination.page + 1;
    this.setState({
      pagination,
    }, () => {
      this.getReportAllList();
      this.setIsNewEnable();
    })
  }

  /*
  * 报表是可以新增的，但是需要具备一定的权限
  * 受 profile 中的字段控制
  * */
  setIsNewEnable = () => {
    let {profile} = this.props;
    if (profile['advanceFunctions'] && profile['advanceFunctions'].indexOf && profile['advanceFunctions'].indexOf("280002000100") > -1) {
      this.setState({
        isNewEnable: true
      })
    } else {
      this.setState({
        isNewEnable: false
      })
    }
  };

  //获取报表类型
  getReportAllList() {
    this.setState({
      loading: true
    });
    let {pagination} = this.state;
    let params = {
      "page": pagination.page,
      "size": pagination.size,
    };
    ReportDistributionService.getReportAllList(params)
      .then((res) => {
        let data = res.data;
        //添加一个序号
        data.map((item, index) => item._index = pagination.page * pagination.size + index + 1);
        pagination.current = pagination.page + 1;
        pagination.total = Number(res.headers['x-total-count']);
        this.setState({
          pagination,
          loading: false,
          reportList: data,
        })
      })
  }

  //分页点击
  onChangePager = (_pagination, filters, sorter) => {
    let {pagination} = this.state;
    pagination.page = _pagination.current - 1;
    this.setState({
      pagination
    }, () => {
      this.getReportAllList();
    })
  };
  //跳转报表详情
  goToReportDetail = (item) => {
    this.setBeforePage(this.state.pagination, 'ReportDistribution');
    let path = menuRoute.getRouteItem('data-report-distribution-permission', 'key').url.replace(':id', item.id);
    let reportName = item.reportName.replace(/\//g, " ");
    path = path.replace(':name', reportName);
    this.context.router.push(path);
  };

  showAddReport = () => {
    this.setState({
      newReport: true,
      reportObj: {
        reportCode: "",
        reportUrl: "",
        reportName: "",
        reportDesc: "",
        i18n: {},
      }
    })
  };
  hideAddReport = () => {
    this.props.form.resetFields();
    this.setState({
      newReport: false
    })
  };

  addReport = (e) => {
    e.preventDefault();
    let {reportObj} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        Object.assign(reportObj,{
          reportCode: values.reportCode,
          reportUrl: values.reportUrl
        });
        this.createReport(reportObj);
      }
    })
  };
  createReport = (report) => {
    this.setState({
      loading: true,
    });
    ReportDistributionService.createReport(report)
      .then((response) => {
        this.getReportAllList();
        this.props.form.resetFields();
        this.hideAddReport();
      })
      .catch((err) => {
        this.setState({
          loading: false,
        })
      })
  };
  //监听表单值
  handleFormChange = () => {
    //有多语言慎用
  };
  i18nChange = (name, i18nName) => {
    const reportObj = this.state.reportObj;
    reportObj.reportName = name;
    if (!reportObj.i18n) {
      reportObj.i18n = {};
    }
    reportObj.i18n.reportName = i18nName
  };
  i18nDescChange = (name, i18nName) => {
    const reportObj = this.state.reportObj;
    reportObj.reportDesc = name;
    if (!reportObj.i18n) {
      reportObj.i18n = {};
    }
    reportObj.i18n.reportDesc = i18nName
  };

  render() {
    const {reportObj, loading, reportList, columns, isNewEnable} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    const {getFieldDecorator} = this.props.form;
    let className = (!isNewEnable) ? 'hide' : "";
    return (
      <div className="report-distribution-wrap">
        <div className="btn-wrap">
          <Button type="primary" className={className}
                  onClick={this.showAddReport}> {messages('data-center.key50')/*新增报表*/}
          </Button>
        </div>

        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total',
              {total: `${this.state.pagination.total}`})}
          </div>
        </div>
        <ResizeTable
          dataSource={reportList}
          columns={columns}
          size="middle"
          onRow={record => ({
            onClick: () => this.goToReportDetail(record)
          })}
          pagination={this.state.pagination}
          onChange={this.onChangePager}
          loading={this.state.loading}
          bordered
        />
        <Modal
          key={this.state.modalKey}
          closable
          width={600}
          className="create-report-modal"
          title={messages('data-center.key50')/*新增报表*/}
          visible={this.state.newReport}
          footer={null}
          onCancel={this.hideAddReport}
          destroyOnClose={true}
        >
          <Form onSubmit={this.addReport} onChange={this.handleFormChange}>
            <FormItem
              {...formItemLayout}
              label={messages('data-center.key33')/*报表名称*/}
              colon={true}>
              {getFieldDecorator('reportName', {
                initialValue: reportObj.reportName,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <div>
                  <LanguageInput
                    key={1}
                    name={reportObj.reportName}
                    i18nName={reportObj.i18n ? reportObj.i18n.reportName : null}
                    isEdit={reportObj.id}
                    nameChange={this.i18nChange}
                  />
                </div>
              )
              }
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={messages('data-center.key51')/*报表描述*/}
              colon={true}>
              {getFieldDecorator('reportDesc', {
                initialValue: reportObj.reportDesc,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <div>
                  <LanguageInput
                    key={2}
                    name={reportObj.reportDesc}
                    i18nName={reportObj.i18n ? reportObj.i18n.reportDesc : null}
                    isEdit={reportObj.id}
                    nameChange={this.i18nDescChange}
                  />
                </div>
              )
              }
            </FormItem>

            <FormItem
              {...formItemLayout}
              label={messages('data-center.key52')/*报表代码*/}
              colon={true}>
              {getFieldDecorator('reportCode', {
                initialValue: reportObj.reportCode,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <Input placeholder={messages("common.please.enter")}/>)
              }
            </FormItem>

            <FormItem
              {...formItemLayout}
              label={messages('data-center.key53')/*URL*/}
              colon={true}>
              {getFieldDecorator('reportUrl', {
                initialValue: reportObj.reportUrl,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  }
                ]
              })(
                <Input placeholder={messages("common.please.enter")}/>)
              }
            </FormItem>
            <div className="role-list-from-footer">
              <Button onClick={this.hideAddReport}>
                {messages('common.cancel')}
              </Button>
              &nbsp;&nbsp;&nbsp;
              <Button type="primary"
                      htmlType="submit"
                      loading={loading}>
                {messages('common.save')}
              </Button>
            </div>
          </Form>
        </Modal>
      </div>
    )
  }
}

ReportDistribution.contextTypes = {
  router: React.PropTypes.object
};
const WrappedReportDistribution = Form.create()(ReportDistribution);

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
  }
}

export default connect(mapStateToProps)(WrappedReportDistribution);
